package com.qyhl.webtv.module_live.teletext.program;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.ProgramDetailBean;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.qyhl.webtv.module_live.utils.Event;
import com.qyhl.webtv.module_live.utils.RadioPlayerService;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/1/4.
 *
 * @author qyhl
 *         电台直播
 */

@Route(path = ARouterPathConstant.LIVE_RADIO)
public class LiveRadioActivity extends BaseActivity implements LiveNormalContract.LiveNormalView {
    @BindView(R2.id.share_btn)
    ImageView shareBtn; //分享
    @BindView(R2.id.cover)
    ImageView cover;   //胶片底部
    @BindView(R2.id.title)
    TextView title;   //节目名称
    @BindView(R2.id.time)
    TextView time;   //时间段
    @BindView(R2.id.menu)
    TextView menu;  //节目单
    @BindView(R2.id.play_time)
    TextView playTime; //已经播放时间
    @BindView(R2.id.total_time)
    TextView totalTime; //总时间
    @BindView(R2.id.progress)
    AppCompatSeekBar seekBar; //进度条
    @BindView(R2.id.progress_layout)
    RelativeLayout progressLayout;
    @BindView(R2.id.play_status)
    ImageView playStatus; //播放按钮
    @BindView(R2.id.previous_btn)
    ImageView previousBtn; //上一曲
    @BindView(R2.id.next_btn)
    ImageView nextBtn;  //下一曲
    @BindView(R2.id.player_layout)
    RelativeLayout playerLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.image_cover)
    ImageView imageCover;  //栏目封面图
    @BindView(R2.id.txt_title)
    TextView txtTitle;  //栏目名称
    @BindView(R2.id.person_num)
    TextView personNum;  //看过人数
    @BindView(R2.id.cover_icon)
    ImageView coverIcon; //胶片封面
    @BindView(R2.id.cover_layout)
    RelativeLayout coverLayout;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    private LiveNormalPresenter mPresenter;

    @Autowired(name = "id")
    String programId;

    private ProgramDetailBean mBean;

    private RadioMenuPop radioMenuPop;

    private LoadingDialog.Builder builder;

    private Timer mTimer;//进度计时器
    private TimerTask mTimerTask;//进度计时任务

    private Timer timer;
    private TimerTask timerTask;

    private int playtime, mProgress;

    private RadioPlayerService mService;//播放服务

    private Intent intent;

    private ObjectAnimator mCircleAnimator;

    private float mValueAvatar = 0f;//记录胶片旋转的角度

    private int mWeekNum, mMenuNum;//记录当前选中的日期和节目

    private Calendar mCalendar;

    private int curDay;//当前日期

    private boolean seekable;//拖动进度是否有效
    private PowerManager.WakeLock wakeLock;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.Transparent));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

    }



    @Override
    protected int getContentView() {
        return R.layout.live_activity_live_radio;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new LiveNormalPresenter(this);
        initView();
        mPresenter.getDetail(programId);
        mPresenter.click(programId);
    }

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onResume() {
        super.onResume();
        /**
         * 禁止自动锁屏，某些手机自动锁屏，服务会被杀死
         */
        wakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                        | PowerManager.ON_AFTER_RELEASE, "LiveRadioActivity");
        wakeLock.acquire();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (wakeLock != null) {
            wakeLock.release();
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        BusFactory.getBus().register(this);
        //服务
        mService = new RadioPlayerService();
        intent = new Intent(this, RadioPlayerService.class);

        //加载动画
        builder = new LoadingDialog.Builder(LiveRadioActivity.this);
        builder.setTitle("切换中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        //设置动画

        initAvatarAnimation(mValueAvatar);

        reset();
    }

    /**
     * 设置监听
     */
    @Override
    protected void setListener() {
        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(programId);
        });

        //分享
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(LiveRadioActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        if (mBean != null) {
                            MShareBoard shareBoard = new MShareBoard(LiveRadioActivity.this,programId,mBean.getProgram().getName(),mBean.getProgram().getCoverImg(),mBean.getProgram().getDetail(), CommonUtils.getInstance().getBannerId(),13);
                            shareBoard.showPopupWindow();
//                            ShareUtils.getInstance().goShare(programId, 13, mBean.getProgram().getDetail(), mBean.getProgram().getName(), mBean.getProgram().getCoverImg(), LiveRadioActivity.this);
                        } else {
                            Toasty.normal(LiveRadioActivity.this, "请等待信息加载...", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(LiveRadioActivity.this);
                    }
                });
            }
        });

        //节目单
        menu.setOnClickListener(v -> radioMenuPop.showPopupWindow());

        //加载动画消失监听
        builder.getmDialog().setOnDismissListener(dialog -> {

        });

        //上一首
        previousBtn.setOnClickListener(v -> {
            try {
                if (mBean.getProgramDay() != null && mBean.getProgramDay().get(mWeekNum).getProgram() != null) {
                    goNext(false);
                } else {
                    Toasty.normal(LiveRadioActivity.this, "暂无节目！").show();
                }
            } catch (Exception e) {
            }

        });

        //下一首
        nextBtn.setOnClickListener(v -> {
            try {
                if (mBean.getProgramDay() != null && mBean.getProgramDay().get(mWeekNum).getProgram() != null) {
                    if (mBean.getProgramDay().get(mWeekNum).getProgram().get(mMenuNum).getStatus() == 0) {
                        Toasty.normal(LiveRadioActivity.this, "当前已经是最新内容了！").show();
                    } else {
                        goNext(true);
                    }
                } else {
                    Toasty.normal(LiveRadioActivity.this, "暂无节目！").show();
                }
            } catch (Exception e) {
            }

        });


        playStatus.setOnClickListener(v -> {
            if (playStatus.getDrawable().getCurrent().getConstantState().equals(ContextCompat.getDrawable(LiveRadioActivity.this, R.drawable.live_radio_playing).getConstantState())) {
                if (mService.getMediaPlayer() != null) {
                    mService.start();
                    mTimer = new Timer();
                    mTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            try {
                                int position = mService.getCurrentPosition();//得到当前歌曲播放进度(秒)
                                Message msg = new Message();
                                msg.what = 3;
                                msg.obj = position;
                                mHandler.sendMessage(msg);
                            } catch (IllegalStateException e) {
                            }
                        }
                    };
                    mTimer.schedule(mTimerTask, 0, 1000);
                    mCircleAnimator.start();
                    playStatus.setImageResource(R.drawable.live_radio_stop);
                } else {
                    firstPlay();
                }
            } else {
                if (mService.getMediaPlayer() != null && mService.getMediaPlayer().isPlaying()) {
                    mService.pause();
                    mCircleAnimator.cancel();
                    initAvatarAnimation(mValueAvatar);
                    playStatus.setImageResource(R.drawable.live_radio_playing);
                }

                if (mTimer != null) {
                    mTimer.cancel();
                }
            }
        });


        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //进度条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    try {
                        mProgress = progress * mService.getDuration() / seekBar.getMax();
                    } catch (Exception e) {
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // seekTo()的参数是相对与影片时间的数字，而不是与seekBar.getMax()相对的数字
                if (seekable) {
                    mService.seekTo(mProgress);
                }

            }
        });

        /**
         * 出错监听
         */
        mService.setErrorListener((mp, what, extra) -> {
            if (builder != null) {
                builder.dismiss();
            }
            mp.reset();
            reset();
            Toasty.normal(LiveRadioActivity.this, "加载出错！").show();
            return true;
        });

        /**
         * 开始监听
         */
        mService.setPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(final MediaPlayer mp) {
                mp.start();
                try {
                    //设置总时长
                    playtime = mp.getDuration();
                    totalTime.setText(secToTime(playtime));
                } catch (Exception e) {
                    time.setText("xx:xx:xx");
                }
                mTimer = new Timer();
                mTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            int position = mService.getCurrentPosition();//得到当前歌曲播放进度(秒)
                            Message msg = new Message();
                            msg.what = 3;
                            msg.obj = position;
                            mHandler.sendMessage(msg);
                        } catch (IllegalStateException e) {
                        }
                    }
                };
//                coverLayout.startAnimation(rotateAnim);
                mTimer.schedule(mTimerTask, 0, 1000);
                mCircleAnimator.start();
            }
        });

        /**
         * 完成监听
         */
        mService.setCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mService.stop();
                if (mTimer != null) {
                    mTimer.cancel();
                }
                reset();
                mCircleAnimator.end();
                goNext(true);
            }
        });

        /**
         * 进度条拖动监听
         */
        mService.setSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete(MediaPlayer mp) {
                try {
                    //设置已播时间
                    playTime.setText(secToTime(mp.getCurrentPosition()));
                } catch (Exception e) {
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 设置详情
     *
     * @param bean
     */
    @Override
    public void setDetail(ProgramDetailBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        mBean = bean;

        mCalendar = Calendar.getInstance();
        curDay = mCalendar.get(Calendar.DAY_OF_MONTH);

        //设置标题，跑马灯
        title.setText("正在播放：" + mBean.getProgram().getName());
        title.setMaxLines(1);
        title.setMarqueeRepeatLimit(3);
        title.setHorizontallyScrolling(true);
        title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        title.setSelected(true);
        title.setFocusable(true);

        if (StringUtils.isNotEmpty(mBean.getProgram().getCoverIcon())) {
            coverIcon.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(mBean.getProgram().getCoverIcon())
                    .apply(new RequestOptions().optionalTransform(new GlideCircleTransform(this)))
                    .into(coverIcon);
        } else {
            coverIcon.setVisibility(View.GONE);
        }

        Glide.with(this)
                .load(mBean.getProgram().getCoverImg())
                .apply(new RequestOptions().optionalTransform(new GlideRoundTransform(4)).placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_error_large_default))
                .into(imageCover);

        txtTitle.setText(mBean.getProgram().getName());

        personNum.setText(StringUtils.transformNum(mBean.getProgram().getHits() + "") + "人听过");

        //设置时间
        time.setText("");

        if (mBean.getProgram().getIsNotice() != 0) {
            menu.setVisibility(View.VISIBLE);
            //初始化选中节目单
            for (int i = 0; i < mBean.getProgramDay().size(); i++) {
                if (mBean.getProgramDay().get(i).getIsLive() == 1) {
                    mWeekNum = i;
                }
                for (int j = 0; j < mBean.getProgramDay().get(i).getProgram().size(); j++) {
                    if (mBean.getProgramDay().get(i).getProgram().get(j).getStatus() == 0) {
                        mMenuNum = j;
                    }
                }
            }
            radioMenuPop = new RadioMenuPop(this, mBean, mWeekNum, mMenuNum);
            radioMenuPop.setPopupWindowFullScreen(true);
            try {
                title.setText("正在播放：" + mBean.getProgramDay().get(mWeekNum).getProgram().get(mMenuNum).getName());
            } catch (Exception e) {
                title.setText("正在播放：" + mBean.getProgram().getName());
            }
        } else {
            menu.setVisibility(View.GONE);
            title.setText("正在播放：" + mBean.getProgram().getName());
        }

        firstPlay();

        //存在节目单时，定时刷新正在播放的节目单
        if (mBean.getProgram().

                getIsNotice() != 0)

        {
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    long time = System.currentTimeMillis();//当前时间
                    int weekPostion = 0;//当前正在直播的日期
                    int menuPostion = 0;//当前正在直播的节目序号
                    for (int i = 0; i < mBean.getProgramDay().size(); i++) {
                        if (mBean.getProgramDay().get(i).getIsLive() == 1) {
                            weekPostion = i;
                        }
                    }
                    for (int i = 0; i < mBean.getProgramDay().get(weekPostion).getProgram().size(); i++) {
                        if (mBean.getProgramDay().get(weekPostion).getProgram().get(i).getStatus() == 0) {
                            menuPostion = i;
                        }
                    }
                    //判断当前播放的是否是今日最后一条
                    if (menuPostion == (mBean.getProgramDay().get(weekPostion).getProgram().size() - 1)) {
                        //判断是否过了一天
                        if (curDay < mCalendar.get(Calendar.DAY_OF_MONTH)) {
                            //判断当前是否在直播最后一条或者没有在播放
                            if ((mWeekNum == weekPostion && menuPostion == mMenuNum) || !mService.getMediaPlayer().isPlaying()) {
                                if (mTimer != null) {
                                    mTimer.cancel();
                                }
                                timer.cancel();
                                mService.getMediaPlayer().stop();
                                mPresenter.getDetail(programId);
                            }
                        }
                    } else {
                        //下一个节目开始时间
                        try {
                            String startTime = mBean.getProgramDay().get(weekPostion).getProgram().get(menuPostion + 1).getStartTime();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            long tTime = simpleDateFormat.parse(startTime).getTime();
                            //判断下一个节目是否已经开始
                            if (time >= tTime) {
                                for (int i = 0; i < mBean.getProgramDay().get(weekPostion).getProgram().size(); i++) {
                                    if (i == (menuPostion + 1)) {
                                        mBean.getProgramDay().get(weekPostion).getProgram().get(i).setStatus(0);
                                    } else if (i < (menuPostion + 1)) {
                                        mBean.getProgramDay().get(weekPostion).getProgram().get(i).setStatus(1);
                                    } else {
                                        mBean.getProgramDay().get(weekPostion).getProgram().get(i).setStatus(2);
                                    }
                                }
                                mHandler.sendEmptyMessage(0);
                                if ((mWeekNum == weekPostion && menuPostion == mMenuNum)) {
                                    mHandler.sendEmptyMessage(1);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            timer.schedule(timerTask, 0, 10000);
        }

    }


    private void firstPlay() {
        if (NetUtil.getNetWorkState(this) == 1) {//判断是否wifi
            playStatus.setImageResource(R.drawable.live_radio_stop);
            seekable = false;
            LiveRadioActivity.this.startService(intent);//启动服务
            mService.initMediaPlayer(mBean.getProgram().getHlsUrl());
        } else {
            new CommonDialog.Builder(LiveRadioActivity.this)
                    .setCancelable(false)
                    .setCanceledOnTouchOutside(false)
                    .setTitle("提示", R.color.global_base)
                    .setMessage("当前处于非wifi状态下，继续播放将消耗您的流量")
                    .setPositiveButton("继续播放", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            playStatus.setImageResource(R.drawable.live_radio_stop);
                            LiveRadioActivity.this.startService(intent);//启动服务
                            seekable = false;
                            mService.initMediaPlayer(mBean.getProgram().getHlsUrl());

                        }
                    }, R.color.global_base).setNegativeButton("停止播放", new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            }, R.color.global_black_lv2).show();
        }
    }

    /**
     * 上一曲或者下一曲
     *
     * @param isNext
     */
    private void goNext(boolean isNext) {
        try {
            if (isNext) {
                if (mMenuNum < mBean.getProgramDay().get(mWeekNum).getProgram().size() - 1) {
                    mMenuNum += 1;
                    builder.show();
                    BusFactory.getBus().post(new Event.RadioEvent(mWeekNum, mMenuNum));
                } else {
                    Toasty.normal(LiveRadioActivity.this, "当前已经是最后一个了！").show();
                }
            } else {
                if (mMenuNum == 0) {
                    Toasty.normal(LiveRadioActivity.this, "当前已经是第一个了！").show();
                } else {
                    mMenuNum -= 1;
                    builder.show();
                    BusFactory.getBus().post(new Event.RadioEvent(mWeekNum, mMenuNum));
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void setNetError(String msg) {
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setNoNetworkText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setEmpty(String msg) {
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setEmptyText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }


    @Override
    public void getPathError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg).show();
    }

    @Override
    public void getPathSuccess(String url) {
        builder.dismiss();
        if (mTimer != null) {
            mTimer.cancel();
        }
        mService.initMediaPlayer(url);
        playStatus.setImageResource(R.drawable.live_radio_stop);
        radioMenuPop.refresh(mWeekNum, mMenuNum);

    }

    @Override
    public void cancel() {
        builder.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.RadioEvent event) {
        if (event != null) {
            mWeekNum = event.getWeekNum();
            mMenuNum = event.getMenuNum();
            ProgramDetailBean.ProgramNoticeList.Program curBean = mBean.getProgramDay().get(mWeekNum).getProgram().get(mMenuNum);
            if (curBean.getStatus() == 0) {
                time.setText(curBean.getsTime() + "-" + DateUtils.teleTextDateFormat(curBean.getEndTime()));
                title.setText("正在播放： " + curBean.getName());
                seekable = false;
                builder.dismiss();
                mService.initMediaPlayer(mBean.getProgram().getHlsUrl());
                radioMenuPop.refresh(mWeekNum, mMenuNum);
            } else {
                seekable = true;
                time.setText(curBean.getsTime() + "-" + DateUtils.teleTextDateFormat(curBean.getEndTime()));
                title.setText("正在播放： " + curBean.getName());
                builder.show();
                mPresenter.getPlayPath(mBean.getProgram().getStreamAddressName(), curBean.getStartTime(), curBean.getEndTime());
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
        mService.stopService();
        if (timer != null) {
            timer.cancel();
        }
    }


    private final Handler mHandler = new MyHandler(this);


    private void reset() {
        playStatus.setImageResource(R.drawable.live_radio_playing);
        playTime.setText("00:00:00");
        totalTime.setText("00:00:00");
        mCircleAnimator.cancel();
        coverLayout.clearAnimation();
    }

    /**
     * 转换时间格式
     *
     * @param time
     * @return
     */
    public String secToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0) {
            return "00:00:00";
        } else {
            second = time / 1000;
            minute = second / 60;
            if (second < 60) {
                timeStr = "00:00:" + unitFormat(second);
            } else if (minute < 60) {
                second = second % 60;
                timeStr = "00:" + unitFormat(minute) + ":" + unitFormat(second);
            } else {//数字>=3600 000的时候
                hour = minute / 60;
                minute = minute % 60;
                second = second - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public String unitFormat(int i) {//时分秒的格式转换
        String retStr = null;
        if (i >= 0 && i < 10) {
            retStr = "0" + Integer.toString(i);
        } else {
            retStr = "" + i;
        }
        return retStr;
    }

    /**
     * 初始化旋转封面动画对象
     *
     * @param start
     */
    private void initAvatarAnimation(float start) {
        mCircleAnimator = ObjectAnimator.ofFloat(coverLayout, "rotation", start, 360f + start);
        mCircleAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mValueAvatar = (Float) animation.getAnimatedValue("rotation");
            }
        });
        mCircleAnimator.setDuration(10000);
        mCircleAnimator.setInterpolator(new LinearInterpolator());
        mCircleAnimator.setRepeatCount(-1);
    }


    private static class MyHandler extends Handler {
        final WeakReference<LiveRadioActivity> mActivity;

        public MyHandler(LiveRadioActivity activity) {
            mActivity = new WeakReference<LiveRadioActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            LiveRadioActivity liveRadioActivity = mActivity.get();
            switch (msg.what) {
                case 0:
                    liveRadioActivity.radioMenuPop.refreshData(liveRadioActivity.mBean);
                    break;
                case 1:
                    liveRadioActivity.radioMenuPop.refresh(liveRadioActivity.mWeekNum, liveRadioActivity.mMenuNum + 1);
                    liveRadioActivity.mMenuNum += 1;
                    break;
                case 3: {
                    int position = (int) msg.obj;
                    int mMax = liveRadioActivity.playtime;//最大秒数
                    int sMax = liveRadioActivity.seekBar.getMax();//seekBar最大值，算百分比
                    try {
                        liveRadioActivity.seekBar.setProgress(position * sMax / mMax);
                    } catch (Exception e) {
                    }
                    liveRadioActivity.playTime.setText(liveRadioActivity.secToTime(position));

                }
                break;
                default:
                    break;
            }
        }

    }


}